<template>
  <el-dialog
    :title="props.title"
    @close="onClose"
    v-model="visible"
    width="1100px"
    :close-on-click-modal="false"
  >
    <div class="main">
      <div style="margin-right: 30px; flex-shrink: 0">
        <content
          :list="list"
          :backgroundImg="formParams.backgroundImg ? formParams.backgroundImg : []"
          :buttonName="formParams.buttonName"
          ref="contentRef"
        />
      </div>
      <div style="flex-shrink: 0">
        <div class="title">基本设置</div>
        <el-form
          :disabled="props.title.includes('详情')"
          :model="formParams"
          ref="formRef"
          :rules="rules"
          label-width="120px"
        >
          <el-form-item label="城市标签" prop="cityName">
            <el-select
              v-model="formParams.cityName"
              @change="handleChangeCity"
              fit-input-width
              placeholder="请选择"
            >
              <el-option
                v-for="item in cityNameOptions"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="礼包名称" prop="packName">
            <el-input
              v-model.trim="formParams.packName"
              placeholder="最多10个字符"
              maxlength="10"
              clearable
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="礼包内容" prop="marCouponPackDetails">
            <el-link
              :disabled="props.title.includes('详情')"
              :underline="false"
              type="primary"
              @click="handleShowList"
              >添加优惠券</el-link
            >
          </el-form-item>
          <el-form-item label="礼包发放上限" prop="count">
            最多
            <el-input-number
              @mousewheel.native.prevent
              :controls="false"
              style="width: 240px"
              v-model="formParams.count"
              :max="100000"
              :min="1"
              :precision="0"
              controls-position="right"
              placeholder="最多100000"
            />份
          </el-form-item>
          <el-form-item label="礼包失效条件" prop="failureCondition">
            <el-radio-group v-model="formParams.failureCondition">
              <el-radio :value="0" :label="0">任意一张优惠券库存不足或失效时礼包失效</el-radio>
              <el-radio :value="1" :label="1">所有优惠券库存不足或失效时礼包失效</el-radio>
            </el-radio-group>
          </el-form-item>
          <div class="title" style="margin-top: 10px">分享设置</div>
          <el-form-item label="分享标题" prop="shareTitle">
            <el-input
              v-model.trim="formParams.shareTitle"
              placeholder="请输入标题名称，最多20字"
              maxlength="20"
              clearable
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="上传图片" prop="shareImg">
            <div
              ><ImageUploadByType
                v-model="formParams.shareImg"
                :isShowTip="false"
                uploadType="1"
                :limit="1"
                :fileSize="10"
              />请上传 大小不超过 10MB 格式为 png/jpg/jpeg 的文件 图片的比例为5:4,
              如500px*400px</div
            >
          </el-form-item>
          <div class="title" style="margin-top: 10px">背景设置</div>
          <el-form-item label="上传背景" prop="backgroundImg">
            <div
              ><ImageUploadByType
                v-model="formParams.backgroundImg"
                :isShowTip="false"
                uploadType="1"
                :limit="1"
                :fileSize="10"
              />请上传 大小不超过10MB，格式为png/jpg/jpeg的文件，图片推荐尺寸750px*2288px</div
            >
          </el-form-item>
          <el-form-item label="按钮文字" prop="buttonName">
            <el-input
              v-model.trim="formParams.buttonName"
              placeholder="请输入按钮文字，最多10字"
              maxlength="10"
              clearable
              style="width: 240px"
            />
          </el-form-item>
          <!-- <div class="title">投放入口设置</div>
          <div style="margin-bottom: 10px">投放入口</div>
          <el-row>
            <el-col :span="2">
              <el-form-item label-width="0">
                <el-checkbox
                  v-model="formParams.popup"
                  label="弹窗"
                  size="large"
                  :true-label="1"
                  :true-value="1"
                  :false-value="0"
                  :false-label="0"
                  style="margin-right: 20px"
                  :checked="formParams.popup === 1"
                  @change="handleCheckboxChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label-width="0" prop="popupUrl">
                <div style="display: flex; align-items: start">
                  上传弹窗图片：

                  <div
                    ><ImageUploadByType
                      v-model="formParams.popupUrl"
                      :isShowTip="false"
                      uploadType="1"
                      :limit="1"
                      :fileSize="10"
                    />图片的比例590px*920px 请上传 大小不超过 10MB 格式为 png/jpg/jpeg 的文件</div
                  >
                </div>
              </el-form-item>
            </el-col>
          </el-row> -->
        </el-form>
      </div>
    </div>
    <template #footer v-if="!props.title.includes('详情')">
      <el-button :loading="submit" type="primary" @click="handleAction(true)"> 保存 </el-button>
      <el-button @click="handleAction(false)">取消</el-button>
    </template>
    <couponList ref="couponListRef" @select="handleSelect" />
  </el-dialog>
</template>

<script setup>
import { checkPopupApi } from '@/api/marketing/activity'
import content from './content.vue'
import couponList from './couponList.vue'
import { addCouponPackApi, getCouponPackDetailApi } from '@/api/marketing/giftPack'
import useGlobalStore from '@/store/modules/global'

const globalStore = useGlobalStore()
const cityNameOptions = computed(() => globalStore.myCityList)

const router = useRouter()
const props = defineProps({
  title: {
    type: String,
    default: ''
  },
  flag: {
    type: Boolean,
    default: false
  }
})
const emit = defineEmits(['refresh'])

const formRef = ref(null)
const couponListRef = ref(null)
const submit = ref(false)

const visible = ref(false)

const formParams = reactive({
  packName: '',
  marCouponPackDetails: [],
  count: null,
  failureCondition: '',
  popup: 0,
  popupUrl: '',
  shareTitle: '',
  shareImg: '',
  backgroundImg: '',
  buttonName: '',
  cityName: ''
})

const checkImg = (rule, value, callback) => {
  if (formParams.popup) {
    if (!value?.length) {
      callback(new Error('请上传弹窗图片'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}

const rules = {
  packName: [{ required: true, message: '请输入礼包名称', trigger: 'blur' }],
  cityName: [{ required: true, message: '请选择', trigger: 'change' }],
  marCouponPackDetails: [
    { required: true, type: 'array', message: '请选择礼包内容', trigger: 'change' }
  ],
  count: [{ required: true, message: '请输入发放上限', trigger: 'change' }],

  failureCondition: [{ required: true, message: '请选择', trigger: 'change' }],

  popupUrl: [{ validator: checkImg, trigger: 'change' }],
  shareTitle: [{ required: true, message: '请输入分享标题', trigger: 'blur' }],
  shareImg: [{ required: true, message: '请上传图片', trigger: 'change' }],
  backgroundImg: [{ required: true, message: '请上传背景', trigger: 'change' }],
  buttonName: [{ required: true, message: '请输入', trigger: 'blur' }]
}

function handleChangeCity() {
  list.value = []
  formParams.marCouponPackDetails = []
}

// 校验弹窗是否被使用
function handleCheckboxChange(val) {
  if (val) {
    formParams.popup = 0
    checkPopupApi({ cityName: formParams.cityName }).then((res) => {
      if (res.data) {
        ElMessageBox.confirm(
          '弹窗已被使用，此活动是否优先使用，使用后替代小程序首页弹窗。',
          '弹窗已被使用',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          }
        )
          .then(() => {
            formParams.popup = 1
          })
          .catch(() => {
            formParams.popup = 0
          })
      } else {
        formParams.popup = 1
      }
    })
  } else {
    formParams.popup = 0
  }
}

function onClose() {
  formRef.value.resetFields()
  list.value = []
  Object.keys(formParams).forEach((key) => {
    formParams[key] = null
  })
  formParams.popup = 0
  formParams.marCouponPackDetails = list.value
  visible.value = false
}

// 选择优惠券
function handleShowList() {
  couponListRef.value.init(list.value, formParams.cityName)
}
const list = ref([])

// 选择优惠券
function handleSelect(val) {
  list.value = val
  formParams.marCouponPackDetails = val
  formRef.value.validateField('marCouponPackDetails')
}

function handleAction(confirm) {
  console.log('formParams.value', formParams)
  if (confirm) {
    submit.value = true
    formRef.value?.validate((valid) => {
      if (valid) {
        // 文本与内容转换成html标签
        const params = { ...formParams }

        // 图片
        const flag = params.popupUrl?.length && params.popup
        params.popupUrl = flag ? params.popupUrl[0].url : ''
        params.popup = flag ? 1 : 0

        params.shareImg = params.shareImg[0].url

        // 背景图片
        params.backgroundImg = params.backgroundImg?.length ? params.backgroundImg[0].url : ''

        params.marCouponPackDetails = params.marCouponPackDetails.map((i) => {
          return {
            ...i,
            couponId: i.id,
            couponCount: i.couponCount
          }
        })
        addCouponPackApi(params)
          .then((res) => {
            submit.value = false
            visible.value = false
            emit('refresh')
            ElMessage({
              message: '新建成功',
              type: 'success'
            })
            if (props.flag) {
              router.push('/market/giftPack')
            }
          })
          .catch((err) => {
            if (err?.code === 213) {
              ElMessage({
                message: err?.msg,
                type: 'error'
              })
              list.value = formParams.marCouponPackDetails.filter((i) => {
                return !err?.data.includes(i.id)
              })
              formParams.marCouponPackDetails = [...list.value]
            }
            submit.value = false
          })
      } else {
        ElMessage({
          message: '提交失败，请校验数据',
          type: 'error'
        })
        submit.value = false
      }
    })
  } else {
    onClose()
  }
}

function init(cityName, id, flag) {
  formParams.id = id
  formParams.cityName = cityName
  if (id) {
    getCouponPackDetailApi(id).then((res) => {
      initDeatil(res.data || {}, flag)
      visible.value = true
    })
    return
  }
  visible.value = true
}

function initDeatil(detail, flag) {
  Object.keys(detail).map((i) => {
    formParams[i] = detail[i]
  })

  formParams.cityName = detail.cityName
  formParams.popupUrl = detail.popupUrl ? [{ url: detail.popupUrl }] : ''
  formParams.shareImg = detail.shareImg ? [{ url: detail.shareImg }] : ''
  formParams.backgroundImg = detail.backgroundImg ? [{ url: detail.backgroundImg }] : ''
  if (flag) {
    // TODO:过滤掉禁用状态的优惠券
    list.value =
      detail.marCouponPackDetails
        ?.filter((i) => i.status === 1 || i.status === 4)
        .filter((i) => i.surplusCount > 1) || []
  } else {
    list.value = detail.marCouponPackDetails || []
  }
  formParams.marCouponPackDetails = [...list.value]
}

defineExpose({
  init
})
</script>

<style lang="scss" scoped>
:deep(.el-dialog__body) {
  padding: 0 10px 0 !important;
}
.main {
  position: relative;
  display: flex;
  justify-content: space-between;
  .title {
    margin-bottom: 20px;
    font-size: 16px;
    font-weight: 600;
  }
  .textarea-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .textarea-info {
    line-height: 18px;
  }
  .upload-wrapper {
    display: flex;
    align-items: start;
  }
  .el-checkbox.el-checkbox--large {
    height: 32px;
  }
}
.el-radio-group .el-radio {
  width: 100%;
}
::v-deep .el-upload-list__item {
  transition: none !important;
}
</style>
